package com.kx.center.auth;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.kx.center.common.Cache;
import com.kx.center.common.Constant;
import com.kx.center.entity.StoreAppAccount;
import com.kx.center.exception.EmptyTokenException;
import com.kx.center.exception.IllegalTokenException;
import com.kx.center.exception.InvalidationTokenException;
import com.kx.center.service.StoreAppAccountService;

public class AuthenticationInterceptor extends HandlerInterceptorAdapter {

	@Autowired
	StoreAppAccountService appAccount;

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {

		if (handler.getClass().isAssignableFrom(HandlerMethod.class)) {

			Authentication authPrivileges = ((HandlerMethod) handler).getMethodAnnotation(Authentication.class);

			if (authPrivileges == null || authPrivileges.validate() == false) {
				return true;
			} else {
				// TODO 校验权限
				String token = request.getHeader("X-Security-Token");
				String secretKey = request.getHeader("X-Security-Key");

				if (!StringUtils.isBlank(token)) {
					Long validity = (Long) Cache.get(Cache.TOKEN, token);
					long current = System.currentTimeMillis() / 1000;

					if (validity != null) {
						if (validity >= current) {
							Cache.set(Cache.TOKEN, token, current + Constant.TOKEN_VAILDITY);

							return true;
						} else {
							throw new InvalidationTokenException("token 失效");
						}
					} else {
						// 到数据库中查询
						StoreAppAccount storeAppAccount = appAccount.findAccountByToken(token);
						if (storeAppAccount == null) {
							// token不合法
							throw new IllegalTokenException("token不合法");
						} else {
							// token合法 但失效
							throw new InvalidationTokenException("token失效");
						}
					}
				} else
					if (!StringUtils.isBlank(secretKey) && StringUtils.equalsIgnoreCase(secretKey, Constant.SECRET)) {
					return true;
				} else if (StringUtils.isBlank(token)) {
					// token 为空 抛出token为空异常 返回给前端
					throw new EmptyTokenException();
				}

				return false;
			}
		} else {
			return true;
		}
	}
}
